'''
# 作者    ： 张莹潇
# 创建时间 ： 20/12/12 15:22
'''
from datetime import time
from app.cta_strategy import (
    CtaTemplate,
    StopOrder,
    TickData,
    BarData,
    TradeData,
    OrderData,
    BarGenerator,
    ArrayManager,
)


class SmoothDegreeStrategy(CtaTemplate):
    """"""

    fixed_size = 1
    exit_time = time(hour=10, minute=5)
    action_time = time(hour=10, minute=6)
    opengate = 9/10000

    parameters = ["opengate", "fixed_size"]

    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)

        self.bg = BarGenerator(self.on_bar)
        self.am = ArrayManager()

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_bar(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

    def on_tick(self, tick: TickData):
        """
        Callback of new tick data update.
        """
        self.bg.update_tick(tick)

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.cancel_all()
        am = self.am

        if bar.datetime.time() <= self.exit_time:
            am.update_bar(bar)

        elif bar.datetime.time() == self.action_time:
            print("am.close",am.close)
            drawbacklist = [(1 - am.close[(-49+i):].min()/am.close[(-50+i)]) for i in range(49)]
            revdrawbacklist = [-(1 - am.close[(-49+i):].max()/am.close[(-50+i)]) for i in range(49)]
            print("draw",drawbacklist)
            import numpy as np
            drawbacklist = np.array(drawbacklist)
            revdrawbacklist = np.array(revdrawbacklist)
            robustind = min([drawbacklist.mean(),revdrawbacklist.mean()])
            print(bar.datetime)
            print(robustind)
            if robustind < self.opengate:
                if bar.close_price > am.close[0]:
                    if self.pos >= 0:
                        self.buy(bar.close_price, 1)
                    elif self.pos < 0:
                        self.cover(bar.close_price, 1)

                else:
                    if self.pos <= 0:
                        self.short(bar.close_price, 1)
                    elif self.pos > 0:
                        self.sell(bar.close_price, 1)
            self.am = ArrayManager()

        self.put_event()

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass
